package com.example.x6.configurationmaintenance.DataBase.TimeTick;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract;
import com.example.x6.configurationmaintenance.Interface.TimeTickDatabase.OnDataBaseChangeListener;
import java.util.concurrent.atomic.AtomicInteger;

public class DatabaseManager {
    private static DatabaseManager instance;
    private static SQLiteOpenHelper sqLiteOpenHelper;
    private AtomicInteger atomicInteger = new AtomicInteger();
    private boolean isWriteOped = false;
    private OnDataBaseChangeListener onDataBaseChangeListener;
    private SQLiteDatabase sqLiteDatabase;

    public static synchronized void initializelnstance(SQLiteOpenHelper helper) {
        synchronized (DatabaseManager.class) {
            if (instance == null) {
                instance = new DatabaseManager();
                sqLiteOpenHelper = helper;
            }
        }
    }

    public void setOnDataBaseChangeListener(OnDataBaseChangeListener onDataBaseChangeListener2) {
        this.onDataBaseChangeListener = onDataBaseChangeListener2;
    }

    public static synchronized DatabaseManager getInstance() {
        DatabaseManager databaseManager;
        synchronized (DatabaseManager.class) {
            if (instance == null) {
                throw new IllegalStateException(ContactsContract.Data.class.getSimpleName() + "is not initialized, call initializenInstance(...) method first");
            }
            databaseManager = instance;
        }
        return databaseManager;
    }

    public synchronized SQLiteDatabase getWritableDatabase() {
        this.isWriteOped = true;
        if (this.atomicInteger.incrementAndGet() == 1) {
            this.sqLiteDatabase = sqLiteOpenHelper.getWritableDatabase();
        }
        return this.sqLiteDatabase;
    }

    public synchronized SQLiteDatabase getReadableDatabase() {
        if (this.atomicInteger.incrementAndGet() == 1) {
            this.sqLiteDatabase = sqLiteOpenHelper.getReadableDatabase();
        }
        return this.sqLiteDatabase;
    }

    public synchronized void closeDatabase() {
        if (this.isWriteOped) {
            if (this.onDataBaseChangeListener != null) {
                this.onDataBaseChangeListener.OnDataBaseChange();
            }
            this.isWriteOped = false;
        }
        if (this.atomicInteger.decrementAndGet() == 0) {
            this.sqLiteDatabase.close();
        }
    }
}
